package com.fjwt.gz.mch.web;

import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.beans.RequestKitBean;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.model.security.GzUserDetails;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/*
* 数据请求拦截器
*
*/
@Slf4j
@Component
public class ApiReqInterceptor implements HandlerInterceptor {

    @Autowired
    private RequestKitBean requestKitBean;

    /**
     * preHandle是在控制器方法执行之前被调用
     *
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        GzUserDetails userDetails = (GzUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 如果加白接口未获取token直接跳过
        if (ObjectUtils.isEmpty(userDetails)){
            log.error("用户信息为空");
            return true;
        }
        Integer paramHashCode = null;
        if ("GET".equals(request.getMethod())) {
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (ObjectUtils.isNotEmpty(parameterMap)) {
                paramHashCode = parameterMap.hashCode();
            }
        }else {
            JSONObject reqParamJSON = requestKitBean.getReqParamJSON();
            if (ObjectUtils.isNotEmpty(reqParamJSON)) {
                paramHashCode = reqParamJSON.hashCode();
            }
        }
        String cacheKey = CS.getCacheKeyReqDebounce(Constants.SYS_ROLE_TYPE.MCH, request.getRequestURI(), userDetails.getFansId(), paramHashCode);

        log.info("cacheKey:{}",cacheKey);
        boolean result = RedisUtil.setIfAbsent(cacheKey, "", 5);
        if (!result) {
            log.info("result:{}", false);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(ApiRes.fail(ApiCodeEnum.CUSTOM_FAIL, "请求频繁").toJSONString());
            response.getWriter().flush();
            response.getWriter().close();
        }

        return result;
    }
}
